﻿/* Copyright (c) 2011-2012, Zetatron Consulting
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Zetatron Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using AionCxxLibrary.Utilities;
using System.Configuration;
using AionCxxLibrary.Models;

namespace AionCxxLibrary.DAO
{
    public class AccountDAO
    {
        public static Account LoadAccount(int accountId)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AuthenticationCatalog"].ToString());
            SqlCommand cmd = new SqlCommand("SELECT Name,Password FROM dbo.Accounts WHERE ID = @AcctID", con);
            cmd.Parameters.Add("@AcctID", SqlDbType.BigInt).Value = accountId;
            Account res = null;
            try
            {
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                if (rdr.Read())
                {
                    res = new Account(accountId);
                    res.Name = rdr["Name"].ToString();
                    res.Password = rdr["Password"].ToString();
                }
            }
            catch (Exception e)
            {
                Log.Error("Cannot load account " + accountId + "!", e);
                res = null;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
            return res;
        }

        public static int Authenticate(string username, string password)
        {
            int result = 0;
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AuthenticationCatalog"].ToString());
            SqlCommand cmd = new SqlCommand("SELECT ID FROM dbo.Accounts WHERE Name = @Name and Password = @Password", con);
            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = username.ToUpper();
            cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = Utility.EncodePassword(username, password);
            try
            {
                con.Open();
                object res = cmd.ExecuteScalar();
                if (res != null) result = int.Parse(res.ToString());
            }
            catch (Exception e)
            {
                Log.Error("Cannot authenticate user!", e);
                result = 0;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
            return result;
        }

        public static int CreateAccount(string username, string password)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AuthenticationCatalog"].ToString());
            SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Accounts(Name, Password) VALUES(@Name, @Password); SELECT @@IDENTITY;", con);
            cmd.Parameters.Add("@Name", System.Data.SqlDbType.VarChar).Value = username.ToUpper();
            cmd.Parameters.Add("@Password", System.Data.SqlDbType.VarChar).Value = Utility.EncodePassword(username, password);
            int result = 0;
            try
            {
                con.Open();
                result = int.Parse(cmd.ExecuteScalar().ToString());
            }
            catch (Exception e)
            {
                Log.Error("Error while creating account!", e);
                result = 0;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
            return result;
        }

        public static void UpdateSession(int accountId, int keyLogin, int keyWorld1, int keyWorld2, int keyReconnect)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AuthenticationCatalog"].ToString());
            SqlCommand cmd = new SqlCommand("DELETE FROM dbo.Sessions WHERE AccountID = @AcctID; INSERT INTO dbo.Sessions(AccountID, KeyLogin, KeyWorld1, KeyWorld2, KeyReconnect) VALUES(@AcctID, @KL, @KW1, @KW2, @KR);", con);
            cmd.Parameters.Add("@AcctID", System.Data.SqlDbType.BigInt).Value = accountId;
            cmd.Parameters.Add("@KL", System.Data.SqlDbType.Int).Value = keyLogin;
            cmd.Parameters.Add("@KW1", System.Data.SqlDbType.Int).Value = keyWorld1;
            cmd.Parameters.Add("@KW2", System.Data.SqlDbType.Int).Value = keyWorld2;
            cmd.Parameters.Add("@KR", SqlDbType.Int).Value = keyReconnect;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Log.Error("Cannot clear sessions for account " + accountId + " !", e);
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
        }

        public static bool CheckSession(int accountId, int keyLogin, int keyWorld1, int keyWorld2)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AuthenticationCatalog"].ToString());
            SqlCommand cmd = new SqlCommand("SELECT COUNT(SessionInternalID) FROM dbo.Sessions WHERE AccountID = @AcctID AND KeyLogin = @KL AND KeyWorld1 = @KW1 AND KeyWorld2 = @KW2", con);
            cmd.Parameters.Add("@AcctID", SqlDbType.BigInt).Value = accountId;
            cmd.Parameters.Add("@KL", SqlDbType.Int).Value = keyLogin;
            cmd.Parameters.Add("@KW1", SqlDbType.Int).Value = keyWorld1;
            cmd.Parameters.Add("@KW2", SqlDbType.Int).Value = keyWorld2;
            bool result = false;
            try
            {
                con.Open();
                int res = int.Parse(cmd.ExecuteScalar().ToString());
                if (res > 0) result = true;
            }
            catch (Exception e)
            {
                Log.Error("Cannot check session!", e);
                result = false;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
            return result;
        }

        public static bool CheckSession(int accountId, int keyLogin)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AuthenticationCatalog"].ToString());
            SqlCommand cmd = new SqlCommand("SELECT COUNT(SessionInternalID) FROM dbo.Sessions WHERE AccountID = @AcctID AND KeyLogin = @KL", con);
            cmd.Parameters.Add("@AcctID", SqlDbType.BigInt).Value = accountId;
            cmd.Parameters.Add("@KL", SqlDbType.Int).Value = keyLogin;
            bool result = false;
            try
            {
                con.Open();
                int res = int.Parse(cmd.ExecuteScalar().ToString());
                if (res > 0) result = true;
            }
            catch (Exception e)
            {
                Log.Error("Cannot check session!", e);
                result = false;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
            return result;
        }

        public static bool CheckSession(int accountId, int keyLogin, int keyReconnect)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AuthenticationCatalog"].ToString());
            SqlCommand cmd = new SqlCommand("SELECT COUNT(SessionInternalID) FROM dbo.Sessions WHERE AccountID = @AcctID AND KeyLogin = @KL AND KeyReconnect = @KR", con);
            cmd.Parameters.Add("@AcctID", SqlDbType.BigInt).Value = accountId;
            cmd.Parameters.Add("@KL", SqlDbType.Int).Value = keyLogin;
            cmd.Parameters.Add("@KR", SqlDbType.Int).Value = keyReconnect;
            bool result = false;
            try
            {
                con.Open();
                int res = int.Parse(cmd.ExecuteScalar().ToString());
                if (res > 0) result = true;
            }
            catch (Exception e)
            {
                Log.Error("Cannot check session!", e);
                result = false;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
            return result;
        }

        public static void ClearSessionsForAccount(int accountId)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AuthenticationCatalog"].ToString());
            SqlCommand cmd = new SqlCommand("DELETE FROM dbo.Sessions WHERE AccountID = @AcctID", con);
            cmd.Parameters.Add("@AcctID", SqlDbType.BigInt).Value = accountId;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Log.Error("Cannot clear sessions for account " + accountId, e);
            }
        }
    }
}
